package com.adingxiong.security.springsecurity.controller;

import com.adingxiong.security.springsecurity.entity.ImageCode;
import com.adingxiong.security.springsecurity.entity.SmsCode;
import com.adingxiong.security.springsecurity.util.ImageCodeUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName TestController
 * @Description TODO
 * @Author xiongchao
 * @Date 2020/10/15 17:27
 **/
@RestController
public class TestController {

    private RequestCache requestCache = new HttpSessionRequestCache();
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    public final static String SESSION_KEY ="code_img_key";

    public final static String MSG_VALID_KEY = "message";


    private ImageCodeUtils imageCodeUtils = new ImageCodeUtils() ;

    private SessionStrategy strategy = new HttpSessionSessionStrategy();

    @GetMapping("/hello")
    public String hello(){
        return "hello spring security";
    }


    @GetMapping("/authentication/require")
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public String requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SavedRequest savedRequest = requestCache.getRequest(request,response);
        if(savedRequest != null){
            String targetUrl = savedRequest.getRedirectUrl();
            if(StringUtils.endsWithIgnoreCase(targetUrl , ".html")){
                redirectStrategy.sendRedirect(request,response,"/login.html");
            }
        }
        return "访问的资源需要权限";
    }

    @GetMapping("/code/img")
    public void initImgCode(HttpServletRequest request,HttpServletResponse response) throws IOException {
        ImageCode imageCode = imageCodeUtils.createImageCode();
        strategy.setAttribute(new ServletWebRequest(request) ,SESSION_KEY,imageCode);
        ImageIO.write(imageCode.getBufferedImage(), "jpeg",response.getOutputStream());
    }


    @GetMapping("/code/sms")
    public void createSmsCode(HttpServletResponse response,HttpServletRequest request,String mobile) {
        SmsCode code = createMsgCode();
        strategy.setAttribute(new ServletWebRequest(request),MSG_VALID_KEY +mobile , code);
        System.out.println("登录验证码为:" + code.getCode() + "有效期为60秒");
    }

    private  SmsCode createMsgCode(){
        int random = (int) ((Math.random()*9+1)*1000);
        return new SmsCode(random+"" ,60);
    }

    @GetMapping("/session/invalid")
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public String sessionValid(){
        return "session已失效，请重新认证";
    }


    @GetMapping("/logout/success")
    public String logout(){
        return "退出成功,请重新登录";
    }

    @GetMapping("/auth/admin")
    @PreAuthorize("hasAuthority('admin')")
    public String authenticationTest() {
        return "您拥有admin权限，可以查看";
    }

}
